package function;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class CreateUser {

    public static void createUser(String username, String password) throws DocumentException, IOException {
        //打开user表,获得所有user节点
        File file = new File("./mydatabase/user/user.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(file);
        List<Node> list = document.getRootElement().selectNodes("user");

        while (true) {
            //判断用户名是否存在
            boolean islegal = true;
            for (Node node : list) {
                Element element = (Element) node;
                Attribute name = element.attribute("name");
                if (name.getText().equals(username)) {
                    System.out.println("用户名已存在，请重新输入");
                    islegal = false;
                    break;
                }
            }
            if (islegal) {
                break;
            } else {
                return;
            }
        }
        document.getRootElement()
                .addElement("user")
                .addAttribute("id", list.size() + 1 + "")
                .addAttribute("name", username)
                .addAttribute("password", password);
        CreateTable.writeIO(file, document);
        createDefaultRole();//创建新用户的权限信息,默认空
        System.out.println("新用户" + username + "创建成功");

    }

    private static void createDefaultRole() throws DocumentException, IOException {
        // 打开 user 表，获得所有 role 节点
        File file = new File("./mydatabase/user/roles.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(file);
        List<Node> list = document.getRootElement().selectNodes("role");

        // 创建新的 role 元素，并添加 id 属性
        Element roleElement = document.getRootElement().addElement("role");
        roleElement.addAttribute("id", String.valueOf(list.size() + 1));

        // 添加 id 子元素
        roleElement.addElement("id").setText(String.valueOf(list.size() + 1));

        // 添加 permissions 子元素
        Element permissionsElement = roleElement.addElement("permissions");
        permissionsElement.addElement("permission"); // 可以在此添加具体的权限内容

        CreateTable.writeIO(file, document);
    }

}
